package util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public final class FileUtil {

	public static File findNextFile(File dir, String preffix, String suffix, int leftZeros) {

		File file = null;

		if (!dir.isDirectory()) {
			throw new IllegalArgumentException(dir + " is not a Directory.");
		}

		int fileNumber = 0;
		
		if(!suffix.startsWith(".")){
			suffix = "."+suffix;
		}

		while (fileNumber < 100) {
			
			fileNumber++;
			
			String strFileNumber = addLeftZero(fileNumber, leftZeros);

			String fileName = preffix + strFileNumber + suffix;

			file = new File(dir, fileName);

			if (!file.exists()) {
				break;
			}

		}

		return file;
	}

	public static String addLeftZero(int value, int leftZeros) {

		StringBuilder strValue = new StringBuilder();
		strValue.append(value);

		while (strValue.length() < leftZeros) {
			strValue.insert(0, "0");
		}

		return strValue.toString();
	}
	
	public static String readFile(File file) throws IOException{
		StringBuilder sb = new StringBuilder();
		if(file != null && file.exists()){
			
			BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
			
			String line;
			
			while((line = bufferedReader.readLine()) != null){
				sb.append(line);
				sb.append("\n");
			}
			
			close(bufferedReader);
			
		}
		
		return sb.toString();
	}
	
	public static void close(Closeable closeable) {
		if (closeable != null) {
			try {
				closeable.close();
			} catch (IOException ignore) {

			}
		}
	}
	
	public static void writeFile(File file, String content) throws IOException{
		
		if(file != null){
			
//			if (!file.exists()) {
//				file.createNewFile();
//			}
			
			BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file, false));
			
			bufferedWriter.write(content);
			bufferedWriter.flush();
			bufferedWriter.close();
		}
		
	}
	
	public static void delete(File file) throws IOException{
		
		boolean deleted = file.delete();
		
		if(!deleted){
			throw new IOException("Unable to delete the file.");
		}
		
	}
	
	public void verifyIsDirectory(File file){
		if(file == null || !file.isDirectory()){
			throw new IllegalArgumentException(file+" is not a directory.");
		}
	}
	
	public void verifyIsFile(File file){
		if(file == null || !file.isFile()){
			throw new IllegalArgumentException(file+" is not a file.");
		}
	}
	
	public static void main(String[] args) {
	  
		System.out.println(findNextFile(new File("C:/temp"), "teste", ".wav", 2));
		
  }
	
}
